package br.edu.unifei.mestrado.fm;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CellList implements Iterable<Cell> {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private Map<Long, Cell> map = new HashMap<Long, Cell>();

	@Override
	public Iterator<Cell> iterator() {
		return map.values().iterator();
	}

	public Cell getCellById(long cellId) {
		return map.get(cellId);
	}

	public Cell createCell(long idCell) {
		Cell cell = 
			new Cell(idCell);
		this.insert(cell);
		return cell;
	}

	public void insert(Cell valor) {
		map.put(valor.getId(), valor);
	}

	public void mostrarLista() {
		logger.info("CellList ({}): {}", map.size(), new Object() {
			@Override
			public String toString() {
				StringBuffer b = new StringBuffer();
				for (Cell cell : map.values()) {
					b.append(cell);
				}
				return b.toString();
			}
		});
	}

	public int size() {
		return map.size();
	}

	void getInitialArbitraryPartition(int size) {
		logger.info("Initial partitions: ");
		int half = size / 2;
		int i = 0;

		for (Cell cell : this) {
			if (i < half) {
				cell.setPartition(1);
			} else {
				cell.setPartition(2);
			}
			i++;
		}
	}

	public void imprimeCellArray() {
		for (final Cell cell : map.values()) {
			logger.debug("CellList: {}", new Object() {
				@Override
				public String toString() {
					StringBuffer b = new StringBuffer();
					if (cell != null) {
						b.append("Cell " + cell.getId() + " Nets:");
						NetList nets = cell.getNets();
						for (Long j = 0L; j < nets.size(); ++j) {
							Net net = nets.getElementAt(j);
							if (net != null) {
								b.append(net.getId() + ", ");
							}
						}
					} else {
						b.append("null");
					}
					return b.toString();
				}
			});
		}
	}

	void printPartitions() {
		String blocoA = "";
		String blocoB = "";
		for (Cell cell : this) {
			if (cell.getPartition() == 1) {
				blocoA += cell.getId() + ",";
			} else {
				blocoB += cell.getId() + ",";
			}
		}
		logger.info("Bloco A: " + blocoA);
		logger.info("Bloco B: " + blocoB);
	}

}
